package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.config.mq.MqCommonUtil;
import com.egoo.ticket.server.config.redis.RedisKeyConstant;
import com.egoo.ticket.server.dao.*;
import com.egoo.ticket.server.pojo.entity.*;
import com.egoo.ticket.server.pojo.vo.EwsDepartmentVo;
import com.egoo.ticket.server.service.EurmDataSyncService;
import com.egoo.ticket.server.service.RoleService;
import com.egoo.ticket.server.service.UserService;
import com.egoo.ticket.server.utils.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EurmDataSyncServiceImpl implements EurmDataSyncService {
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;
	@Autowired
	private EwsUserDao ewsUserDao;
	@Autowired
	private EwsUserRoleDao ewsUserRoleDao;
	@Autowired
	private EwsRoleDao ewsRoleDao;
	@Autowired
	private EwsDepartmentDao ewsDepartmentDao;
	@Autowired
	private CommonUtil commonUtil;
	@Value("${eurmSynData.limit}")
	private Integer limit;
	@Value("${eurmSynData.tenantId}")
	private String eurmTenatIdCode;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private MqCommonUtil mqCommonUtil;
	@Value("${server.eurm-server-url}")
	private String eurmUrl;
	@Value("${server.eurm-uuif-url}")
	private String eurmUuifUrl;
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private WorkOrderFilterMenuDao workOrderFilterMenuDao;
	@Autowired
	private WorkOrderStatusDao workOrderStatusDao;
	@Autowired
	private WorkOrderTypeMenuDao workOrderTypeMenuDao;

	/**
	 * @Author: Donny_dong
	 * @Description: 同步用户数据
	 * @Param:
	 * @return:
	 * @Date: 2020/12/1
	 */
	@Override
	public DbResponse syncUser(JSONObject jsonObject) {
		try {
			JSONObject info = jsonObject.getJSONObject("info");
			String opType = info.getString("opType");
			JSONArray data = info.getJSONArray("data");
			if (CollectionUtils.isEmpty(data)) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE,
						"推送的用户信息为空，不能同步！");
			}
			Map<String, List> userData = getUserData(data);
			List<EwsUser> users = userData.get("user");
			List<EwsUserRole> userRoles = userData.get("userRole");
			if (CollectionUtils.isEmpty(users)
					|| CollectionUtils.isEmpty(userRoles)) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE, "用户数据为空");
			}
			String tenantId = users.get(0).getTenantId();
			List<String> userIds = users.stream().map(ewsUser -> ewsUser.getId()).collect(Collectors.toList());
			Map<String, Object> map = new HashMap<>();
			map.put("tenantId", tenantId);
			map.put("userIds", userIds);
			if (ConstantCode.SynEurmOpType.INSERT.equals(opType)) {
				ewsUserDao.insertBatch(users);
				if (!CollectionUtils.isEmpty(userRoles)) {
					ewsUserRoleDao.insertBatch(userRoles);
				}
			} else if (ConstantCode.SynEurmOpType.UPDATE.equals(opType)) {
				List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(map);
				if (!CollectionUtils.isEmpty(ewsUsers)) {
					ewsUserDao.updateBatch(users);
				} else {
					ewsUserDao.insertBatch(users);
				}
				ewsUserRoleDao.deleteByMap(map);
				if (!CollectionUtils.isEmpty(userRoles)) {
					ewsUserRoleDao.insertBatch(userRoles);
				}
			} else {
				ewsUserDao.deleteByMap(map);
				ewsUserRoleDao.deleteByMap(map);
			}
			log.info("同步用户数据成功!");
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "同步用户数据成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("同步用户数据异常:" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "同步用户数据异常");
		}
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 同步角色数据
	 * @Param:
	 * @return:
	 * @Date: 2020/12/1
	 */
	@Override
	public DbResponse syncRole(JSONObject jsonObject) {
		try {
			JSONObject info = jsonObject.getJSONObject("info");
			String opType = info.getString("opType");
			JSONArray data = info.getJSONArray("data");
			if (CollectionUtils.isEmpty(data)) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE,
						"推送的角色信息为空，无法同步！");
			}
			List<EwsRole> roleData = getRoleData(data);
			String tenantId = data.getJSONObject(0).getString("orgCode");
			Map<String, Object> map = new HashMap<>();
			List<String> roleIds = roleData.stream().map(ewsRole -> ewsRole.getId()).collect(Collectors.toList());
			map.put("tenantId", tenantId);
			map.put("roleIds", roleIds);
			if (ConstantCode.SynEurmOpType.INSERT.equals(opType)) {
				ewsRoleDao.insertBatch(roleData);
			} else if (ConstantCode.SynEurmOpType.UPDATE.equals(opType)) {
				List<EwsRole> ewsRoles = ewsRoleDao.selectRolesListByCondition(map);
				if (!CollectionUtils.isEmpty(ewsRoles)) {
					ewsRoleDao.updateBatch(roleData);
				} else {
					ewsRoleDao.insertBatch(roleData);
				}
			} else {
				ewsRoleDao.delete(map);
			}
			log.info("角色数据同步成功!");
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "角色数据同步成功");
		} catch (Exception e) {
			log.error("同步角色数据异常:" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "同步角色数据异常");
		}
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 同步部门数据
	 * @Param:
	 * @return:
	 * @Date: 2020/12/1
	 */
	@Override
	public DbResponse syncDept(JSONObject jsonObject) {
		try {
			JSONObject info = jsonObject.getJSONObject("info");
			String opType = info.getString("opType");
			JSONArray data = info.getJSONArray("data");
			if (CollectionUtils.isEmpty(data)) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE,
						"推送的部门数据为空，无法同步");
			}
			List<EwsDepartment> deptData = getDeptData(data);
			String tenantId = data.getJSONObject(0).getString("orgCode");
			Map<String, Object> map = new HashMap<>();
			List<String> deptIds = deptData.stream().map(ewsDepartment -> ewsDepartment.getId()).collect(Collectors.toList());
			map.put("tenantId", tenantId);
			map.put("deptIds", deptIds);
			if (ConstantCode.SynEurmOpType.INSERT.equals(opType)) {
				ewsDepartmentDao.insertBatch(deptData);
			} else if (ConstantCode.SynEurmOpType.UPDATE.equals(opType)) {
				List<EwsDepartmentVo> ewsDepartmentVos = ewsDepartmentDao.selectDepartmentListByCondition(map);
				if (!CollectionUtils.isEmpty(ewsDepartmentVos)) {
					ewsDepartmentDao.updateBatch(deptData);
				} else {
					ewsDepartmentDao.insertBatch(deptData);
				}
			} else {
				ewsDepartmentDao.delete(map);
			}
			log.info("同步部门数据成功!");
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "同步部门数据成功");
		} catch (Exception e) {
			log.error("同步部门数据异常:" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "同步部门数据异常");
		}
	}

	/**
	 * TODO 获取内管数据对象总数
	 *
	 * @param dataType 1
	 * @author: victor_tang
	 * @createtime: 2020/12/8 14:46
	 * @return: com.egoo.ticket.server.utils.common.DbResponse
	 */
	@Override
	public Integer getEurmCountByDataType(String dataType, JSONArray filters) {
		log.info("获取内管数据对象总数的dataType为：" + dataType);
		JSONObject bodyJsonObj = new JSONObject();
		bodyJsonObj.put("dataType", dataType);
		bodyJsonObj.put("offset", 0);
		bodyJsonObj.put("limit", 1);
		if (!CollectionUtils.isEmpty(filters)) {
			bodyJsonObj.put("filters", filters);
		}
		JSONObject jsonObject = commonUtil.pubEurmGetData(bodyJsonObj);
		return jsonObject.getInteger("total");
	}

	/**
	 * TODO 获取内管对应数据列表
	 *
	 * @param conditionJsonObject 1
	 * @author: victor_tang
	 * @createtime: 2020/12/8 15:56
	 * @return: com.alibaba.fastjson.JSONArray
	 */
	@Override
	public JSONArray getEurmDataByCondition(JSONObject conditionJsonObject) {
		JSONObject jsonObject = commonUtil.pubEurmGetData(conditionJsonObject);
		return jsonObject.getJSONArray("data");
	}

	/**
	 * TODO 全量同步内管数据
	 *
	 * @param tenantId 1
	 * @param dataType 2
	 * @author: victor_tang
	 * @createtime: 2020/12/8 16:06
	 * @return: com.egoo.ticket.server.utils.common.DbResponse
	 */
	@Override
	public void batchPushSynPramaToMq(String tenantId, String dataType) {
		if (StringUtils.isEmpty(tenantId)) {
			log.error("租户id不能为空！");
			return;
		}
		if (StringUtils.isEmpty(dataType)) {
			log.error("同步数据类型不能为空！");
			return;
		}
		// 获取调取内管次数
		Integer requestCount = getRequestCount(tenantId, dataType);
		if (requestCount == 0) {
			log.info("租户" + tenantId + "的" + dataType + "数据为空，无需同步！");
			return;
		}
		for (int i = 0; i < requestCount; i++) {
			// 获取当前偏移量
			int curentOffset = getCurrentOffSet(tenantId, dataType);
			// 推送同步参数至MQ
			pushSynParamData(tenantId, dataType, curentOffset);
		}
		// 初始化偏移量
		redisUtil.del(RedisKeyConstant.WORK_ORDER_SYN_EURM_OFFSET_PREFX + tenantId + "_" + dataType);
	}

	/**
	 * TODO 批量同步用户信息
	 *
	 * @param conditionJsonObject 1
	 * @author: victor_tang
	 * @createtime: 2020/12/8 17:48
	 * @return: com.egoo.ticket.server.utils.common.DbResponse
	 */
	@Override
	public synchronized DbResponse batchSynUserData(JSONObject conditionJsonObject) {
		try {
			String offset = conditionJsonObject.getString("offset");
			// 获取租户id
			String tenantId = commonUtil.getTenantId(conditionJsonObject);
			if (StringUtils.isEmpty(tenantId)) {
				log.error("请求内管用户数据的租户id不能为空！");
				return new DbResponse(ResponseConstant.RES_FAIL_CODE, "请求内管用户数据的租户id不能为空！");
			}
			// 获取用户数据列表
			JSONArray dataList = getEurmDataByCondition(conditionJsonObject);
			// 根据userName过滤重复用户数据
			dataList = filterRepeatData(dataList);
			// 组装用户数据
			List<EwsUser> ewsUserList = handleUserInfo(dataList);
			List<EwsUserRole> ewsUserRoleList = handleUserRoleRelation(dataList);
			// 批量新增
			if (ewsUserList != null && ewsUserList.size() > 0
					&& ewsUserRoleList != null && ewsUserRoleList.size() > 0) {
				if ("0".equals(offset)) {
					ewsUserRoleDao.deleteAllUserRole(tenantId);
					// 删除用户数据，初始化序列
					ewsUserDao.deleteAllUser(tenantId);
				}
				userService.addUserBatch(ewsUserList, ewsUserRoleList);
				log.info("系统用户及用户角色关系同步成功！");
			}
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "系统用户及用户角色关系同步成功！");
		} catch (Exception e) {
			log.info("系统用户及用户角色关系同步异常：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "系统用户及用户角色关系同步异常：" + e);
		}
	}

	/**
	 * TODO 根据userName过滤重复用户数据
	 *
	 * @param dataList 1
	 * @author: victor_tang
	 * @createtime: 2020/2/24 12:22
	 * @return: com.alibaba.fastjson.JSONArray
	 */
	private JSONArray filterRepeatData(JSONArray dataList) {
		if (dataList == null || dataList.isEmpty()) {
			return null;
		}
		JSONArray returnData = new JSONArray();
		Set<String> userNameSets = new HashSet<>();
		for (int i = 0; i < dataList.size(); i++) {
			JSONObject jsonObject1 = dataList.getJSONObject(i);
			String userName = jsonObject1.getString("userName");
			if (org.apache.commons.lang3.StringUtils.isEmpty(userName)) {
				continue;
			}
			if (userNameSets.contains(userName.toLowerCase())) {
				continue;
			}
			userNameSets.add(userName.toLowerCase());
			returnData.add(jsonObject1);
		}
		return returnData;
	}

	/**
	 * TODO 处理用户信息
	 *
	 * @param dataList 1
	 * @author: victor_tang
	 * @createtime: 2020/2/26 11:59
	 * @return: java.util.List<com.egoo.ticket.server.vo.EwsUser>
	 */
	private List<EwsUser> handleUserInfo(JSONArray dataList) {
		List<EwsUser> ewsUserList = new ArrayList<EwsUser>();
		for (int i = 0; i < dataList.size(); i++) {
			// 组装用户信息
			EwsUser ewsUser = new EwsUser();
			JSONObject jsonObject = dataList.getJSONObject(i);
			String id = jsonObject.getString("userName");
			ewsUser.setId(id);

			String roleCode = jsonObject.getString("code");
			ewsUser.setCode(roleCode);

			String roleName = jsonObject.getString("name");
			ewsUser.setName(roleName);

			String userName = jsonObject.getString("userName");
			ewsUser.setUserName(userName);

			String phone = jsonObject.getString("phone");
			ewsUser.setPhone(phone);
			String email = jsonObject.getString("email");
			ewsUser.setEmail(email);
			String deptId = jsonObject.getString("deptGroup");
			ewsUser.setDepartmentId(deptId);
			String isLeader = jsonObject.getString("responsible");
			ewsUser.setIsLeader(isLeader);
			String tenantId = jsonObject.getString("orgCode");

			if (org.apache.commons.lang3.StringUtils.isEmpty(tenantId)) {
				continue;
			}
			ewsUser.setTenantId(tenantId);

			ewsUserList.add(ewsUser);
		}
		return ewsUserList;
	}

	/**
	 * TODO 处理用户角色关系信息
	 *
	 * @param dataList 1
	 * @author: victor_tang
	 * @createtime: 2020/2/26 11:59
	 * @return: java.util.List<com.egoo.ticket.server.vo.EwsUserRole>
	 */
	private List<EwsUserRole> handleUserRoleRelation(JSONArray dataList) {
		List<EwsUserRole> ewsUserRoleList = new ArrayList<EwsUserRole>();
		for (int i = 0; i < dataList.size(); i++) {
			JSONObject userObj = dataList.getJSONObject(i);
			JSONArray roleList = userObj.getJSONArray("roles");
			for (int j = 0; j < roleList.size(); j++) {
				// 组装用户信息
				EwsUserRole ewsUserRole = new EwsUserRole();
				if (!userObj.isEmpty()) {
					ewsUserRole.setUserId(userObj.getString("userName"));
				}
				JSONObject roleObj = roleList.getJSONObject(j);
				if (!roleObj.isEmpty()) {
					ewsUserRole.setRoleId(roleObj.getString("uuid"));
					ewsUserRole.setTenantId(roleObj.getString(eurmTenatIdCode));
				}
				if (ewsUserRole.getRoleId() != null && ewsUserRole.getUserId() != null) {
					ewsUserRoleList.add(ewsUserRole);
				}
			}
		}
		return ewsUserRoleList;
	}

	/**
	 * TODO 批量同步角色信息
	 *
	 * @param conditionJsonObject 1
	 * @author: victor_tang
	 * @createtime: 2020/12/8 17:48
	 * @return: com.egoo.ticket.server.utils.common.DbResponse
	 */
	@Override
	public synchronized DbResponse batchSynRoleData(JSONObject conditionJsonObject) {
		try {
			String offset = conditionJsonObject.getString("offset");
			// 获取租户id
			String tenantId = commonUtil.getTenantId(conditionJsonObject);
			if (StringUtils.isEmpty(tenantId)) {
				log.error("请求内管用户数据的租户id不能为空！");
				return new DbResponse(ResponseConstant.RES_FAIL_CODE, "请求内管用户数据的租户id不能为空！");
			}
			List<EwsRole> ewsRoleList = new ArrayList<EwsRole>();
			// 获取用户数据列表
			JSONArray dataList = getEurmDataByCondition(conditionJsonObject);
			for (int i = 0; i < dataList.size(); i++) {
				EwsRole ewsRole = new EwsRole();
				String id = dataList.getJSONObject(i).getString("uuid");
				ewsRole.setId(id);
				String roleCode = dataList.getJSONObject(i).getString("code");
				ewsRole.setCode(roleCode);
				String roleName = dataList.getJSONObject(i).getString("name");
				ewsRole.setName(roleName);
				ewsRole.setTenantId(tenantId);
				ewsRoleList.add(ewsRole);
			}
			// 批量新增
			if (ewsRoleList.size() > 0) {
				if ("0".equals(offset)) {
					ewsRoleDao.deleteAllRole(tenantId);
				}
				roleService.addRoleBatch(ewsRoleList);
				log.info("系统角色同步成功！");
			}
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "系统角色同步成功！");
		} catch (Exception e) {
			log.info("系统角色信息同步异常" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "系统角色信息同步异常" + e);
		}
	}

	/**
	 * TODO 批量同步行政组信息
	 *
	 * @param conditionJsonObject 1
	 * @author: victor_tang
	 * @createtime: 2020/12/8 17:48
	 * @return: com.egoo.ticket.server.utils.common.DbResponse
	 */
	@Override
	public synchronized DbResponse batchSynDeptGroupData(JSONObject conditionJsonObject) {
		try {
			String offset = conditionJsonObject.getString("offset");
			// 获取租户id
			String tenantId = commonUtil.getTenantId(conditionJsonObject);
			if (StringUtils.isEmpty(tenantId)) {
				log.error("请求内管用户数据的租户id不能为空！");
				return new DbResponse(ResponseConstant.RES_FAIL_CODE,
						"请求内管行政组数据的租户id不能为空！");
			}
			// 获取用户数据列表
			JSONArray dataList = getEurmDataByCondition(conditionJsonObject);
			if (CollectionUtils.isEmpty(dataList)) {
				log.info("获取部门信息为空！");
				return new DbResponse(ResponseConstant.RES_FAIL_CODE, "获取部门信息为空");
			}
			// 处理部门信息
			List<EwsDepartment> ewsDepartments = handleDeptInfo(dataList);
			if (!CollectionUtils.isEmpty(ewsDepartments)) {
				ewsDepartments.stream().map(ewsDepartment -> ewsDepartment.setTenantId(tenantId)).collect(Collectors.toList());
				// 删除部门所有信息
				if ("0".equals(offset)) {
					ewsDepartmentDao.deleteAllDept(tenantId);
				}
				// 同步部门数据至数据库
				ewsDepartmentDao.insertBatch(ewsDepartments);
			}
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "部门信息同步成功！");
		} catch (Exception e) {
			log.error("获取部门信息异常信息：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "获取部门信息异常：" + e);
		}
	}

	/**
	 * TODO 处理部门信息数据
	 *
	 * @param dataList 1
	 * @author: victor_tang
	 * @createtime: 2020/3/17 12:31
	 * @return: java.util.List
	 */
	private List handleDeptInfo(JSONArray dataList) {
		List<EwsDepartment> ewsDepartments = new ArrayList<>();
		for (int i = 0; i < dataList.size(); i++) {
			EwsDepartment ewsDepartment = new EwsDepartment();
			JSONObject jsonObject = dataList.getJSONObject(i);
			ewsDepartment.setId(jsonObject.getString("code"));
			ewsDepartment.setName(jsonObject.getString("name"));
			ewsDepartment.setPid(jsonObject.getString("parent"));
			String tenantId = jsonObject.getString("orgCode");
			ewsDepartment.setTenantId(tenantId);
			ewsDepartments.add(ewsDepartment);
		}
		return ewsDepartments;
	}

	/**
	 * TODO 推送同步参数至MQ
	 *
	 * @param tenantId     1
	 * @param dataType     2
	 * @param curentOffset 3
	 * @author: victor_tang
	 * @createtime: 2020/12/8 17:06
	 * @return: void
	 */
	private void pushSynParamData(String tenantId, String dataType, int curentOffset) {
		JSONObject bodyJsonObj = new JSONObject();
		bodyJsonObj.put("dataType", dataType);
		bodyJsonObj.put("offset", curentOffset);
		bodyJsonObj.put("limit", limit);
		JSONArray filters = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", eurmTenatIdCode);
		jsonObject.put("type", 0);
		jsonObject.put("value", tenantId);
		filters.add(jsonObject);
		bodyJsonObj.put("filters", filters);
		mqCommonUtil.pushToMsgSyneurmdataQueue(bodyJsonObj.toJSONString());
	}

	/**
	 * TODO 获取当前偏移量，设置下次偏移量
	 *
	 * @param dataType 1
	 * @author: victor_tang
	 * @createtime: 2020/12/8 16:54
	 * @return: int
	 */
	private int getCurrentOffSet(String tenantId, String dataType) {
		String offset =
				redisUtil.getStr(RedisKeyConstant.WORK_ORDER_SYN_EURM_OFFSET_PREFX + tenantId + "_" + dataType);
		int nextOffset;
		int curentOffset;
		if (StringUtils.isEmpty(offset)) {
			nextOffset = limit;
			curentOffset = 0;
		} else {
			nextOffset = Integer.valueOf(offset) + limit;
			curentOffset = Integer.valueOf(offset);
		}
		redisUtil.set(RedisKeyConstant.WORK_ORDER_SYN_EURM_OFFSET_PREFX + tenantId + "_" + dataType, nextOffset + "");
		return curentOffset;
	}

	/**
	 * TODO 获取请求次数
	 *
	 * @param tenantId 1
	 * @param dataType 2
	 * @author: victor_tang
	 * @createtime: 2020/12/8 16:25
	 * @return: java.lang.Integer
	 */
	private Integer getRequestCount(String tenantId, String dataType) {
		Integer dataCount = getDataCount(tenantId, dataType);
		if (dataCount == 0) {
			return 0;
		}
		int count = dataCount / limit;
		int index = dataCount % limit;
		if (count==0) {
			return 1;
		}
		if (index==0) {
			return count;
		}
		return count + 1;
	}

	/**
	 * TODO 获取总数
	 *
	 * @param tenantId 1
	 * @param dataType 2
	 * @author: victor_tang
	 * @createtime: 2020/12/8 16:20
	 * @return: void
	 */
	private Integer getDataCount(String tenantId, String dataType) {
		JSONArray filters = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", eurmTenatIdCode);
		jsonObject.put("type", 0);
		jsonObject.put("value", tenantId);
		filters.add(jsonObject);
		return getEurmCountByDataType(dataType, filters);
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 解析部门数据
	 * @Param:
	 * @return:
	 * @Date: 2020/12/1
	 */
	private List getDeptData(JSONArray data) {
		List<EwsDepartment> ewsDepartments = new ArrayList<>();
		for (int i = 0; i < data.size(); i++) {
			EwsDepartment ewsDepartment = new EwsDepartment();
			JSONObject jsonObject = data.getJSONObject(i);
			String pid = jsonObject.getString("parent");
			String code = jsonObject.getString("code");
			String name = jsonObject.getString("name");
			String tenantId = jsonObject.getString("orgCode");
			if (StringUtils.isEmpty(tenantId)) {
				continue;
			}
			ewsDepartment.setId(code);
			ewsDepartment.setPid(pid);
			ewsDepartment.setName(name);
			ewsDepartment.setTenantId(tenantId);
			ewsDepartments.add(ewsDepartment);
		}
		return ewsDepartments;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 解析用户数据
	 * @Param:
	 * @return:
	 * @Date: 2020/12/1
	 */
	private Map<String, List> getUserData(JSONArray data) {
		List<EwsUser> ewsUsers = null;
		List<EwsUserRole> ewsUserRoles = null;
		Map<String, List> map = new HashMap<>();
		for (int i = 0; i < data.size(); i++) {
			ewsUsers = new ArrayList<>();
			EwsUser ewsUser = new EwsUser();
			JSONObject objectUser = data.getJSONObject(i);
			JSONArray roles = objectUser.getJSONArray("roles");
			String userName = objectUser.getString("userName");
			String name = objectUser.getString("name");
			String dept = objectUser.getString("deptGroup");
			String tenantId = objectUser.getString("orgCode");
			String phone = objectUser.getString("phone");
			String email = objectUser.getString("email");
			ewsUser.setId(userName);
			ewsUser.setCode(userName);
			ewsUser.setUserName(userName);
			ewsUser.setName(name);
			ewsUser.setDepartmentId(dept);
			ewsUser.setTenantId(tenantId);
			ewsUser.setPhone(phone);
			ewsUser.setEmail(email);
			ewsUsers.add(ewsUser);
			if (CollectionUtils.isEmpty(roles)) {
				continue;
			}
			for (int j = 0; j < roles.size(); j++) {
				ewsUserRoles = new ArrayList<>();
				EwsUserRole ewsUserRole = new EwsUserRole();
				JSONObject roleJSONObject = roles.getJSONObject(j);
				ewsUserRole.setRoleId(roleJSONObject.getString("uuid"));
				ewsUserRole.setUserId(userName);
				ewsUserRole.setTenantId(tenantId);
				ewsUserRoles.add(ewsUserRole);
			}
		}
		map.put("user", ewsUsers);
		map.put("userRole", ewsUserRoles);
		return map;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 解析角色数据
	 * @Param:
	 * @return:
	 * @Date: 2020/12/1
	 */
	private List getRoleData(JSONArray data) {
		List<EwsRole> ewsRoles = new ArrayList<>();
		for (int i = 0; i < data.size(); i++) {
			EwsRole ewsRole = new EwsRole();
			JSONObject jsonObject = data.getJSONObject(i);
			String uuid = jsonObject.getString("uuid");
			String code = jsonObject.getString("code");
			String name = jsonObject.getString("name");
			String tenantId = jsonObject.getString("orgCode");
			if (StringUtils.isEmpty(tenantId)) {
				continue;
			}
			ewsRole.setId(uuid);
			ewsRole.setCode(code);
			ewsRole.setName(name);
			ewsRole.setTenantId(tenantId);
			ewsRoles.add(ewsRole);

		}
		return ewsRoles;
	}

	@Override
	public List<String> getRestDay(Integer year) {

		String eurmRequestUrl = eurmUuifUrl + "/if/iam/holiday/list/"+year+".ptc" ;
		Map<String, Object> map = new HashMap<>();
		map.put("__org","default");
		List<String> resultList = new ArrayList<>();
		try {
			String result = restTemplate.getForObject(eurmRequestUrl, String.class, map);
			log.info("获取内管的休息日结果为："+result);
			JSONObject jsonResult = JSON.parseObject(result);
			JSONObject info = jsonResult.getJSONObject("info");
			JSONArray dataArray = info.getJSONArray("data");
			if (CollectionUtils.isEmpty(dataArray)){
				return resultList;
			}
			for (int i = 0; i < dataArray.size(); i++) {
				String days = dataArray.getJSONObject(i).getString("Days");
				resultList.add(days);
			}
		} catch (RestClientException e) {
			e.printStackTrace();
			log.info("获取休息日异常"+e);
		}
		return resultList;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 根据内管租户，进行数据库脚本铺底
	 * @Param:
	 * @return:
	 * @Date: 2021/1/12
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public DbResponse initDBData(List<String> arrayList) {
		List<WorkOrderFilterMenu> defaultData = workOrderFilterMenuDao.selectSysFilterMenu(0L, "default");
		WorkOrderTypeMenu defaulWorkOrderTypeMenu = workOrderTypeMenuDao.selectByWorkOrderTypeId(0L, "default");
		List<WorkOrderStatus> defaultWorkOrderStatus = workOrderStatusDao.selectAllData("default");
		List<String> tenants = workOrderFilterMenuDao.selectTenant();
		arrayList.removeAll(tenants);
		if (CollectionUtils.isEmpty(arrayList)){
			log.info(tenants+"的租户已存在，不需要铺底数据");
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.ADD_SUCCESS_MSG);
		}
		try {
			for (String s :arrayList) {
				List<WorkOrderFilterMenu> workOrderFilterMenus = workOrderFilterMenuDao.selectSysFilterMenu(0L, s);
				WorkOrderTypeMenu workOrderTypeMenus = workOrderTypeMenuDao.selectByWorkOrderTypeId(0L, s);
				List<WorkOrderStatus> workOrderStatus = workOrderStatusDao.selectAllData(s);
				Timestamp timestamp = new Timestamp(System.currentTimeMillis());
				if (CollectionUtils.isEmpty(workOrderFilterMenus)) {

					List<WorkOrderFilterMenu> collect = defaultData.stream()
							.map(workOrderFilterMenu ->
									workOrderFilterMenu.setTenantId(s)
											.setCreateUserId("0")
											.setCreateUserName("系统")
											.setCreateTime(timestamp)
											.setLastUpdateTime(timestamp)
											.setFilterMenuDataType("all")
											.setFilterMenuDataTypeIds("")
											.setFilterMenuVisibleType("all")
											.setFilterMenuVisibleIds("")
											.setLastUserId("0")
											.setLastUserName("系统")).collect(Collectors.toList());

					workOrderFilterMenuDao.insertByBatch(collect);
				if (Objects.isNull(workOrderTypeMenus)){
					defaulWorkOrderTypeMenu.setCreateUserId("0")
											.setCreateUserName("系统")
											.setCreateTime(timestamp)
											.setLastUserId("0")
											.setLastUserName("系统")
											.setTenantId(s)
											.setMenuVisibleType("all")
											.setMenuVisibleIds("")
											.setLastUpdateTime(timestamp);
					workOrderTypeMenuDao.insertMenu(defaulWorkOrderTypeMenu);
				}
				if (CollectionUtils.isEmpty(workOrderStatus)){
					List<WorkOrderStatus> statuses = defaultWorkOrderStatus.stream()
											.map(w -> w.setTenantId(s)
											.setCreateUserId("0")
											.setCreateUserName("系统")
											.setCreateTime(timestamp)
											.setLastUpdateTime(timestamp)
											.setLastUserId("0")
											.setLastUserName("系统")).collect(Collectors.toList());
					workOrderStatusDao.insertBatch(statuses);
				}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("根据租户铺地数据库异常："+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"根据租户铺地数据库异常");
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"ok");
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取内管全量租户
	 * @Param:
	 * @return:
	 * @Date: 2021/1/12
	 */
	@Override
	public List<String> getTenant() {
		try {
			String eurmRequestUrl = eurmUrl + "/if/data/transfer/orgList";
			Map<String, Object> map = new HashMap<>();
			String result = restTemplate.getForObject(eurmRequestUrl, String.class, map);
			log.info("获取内管租户返回的结果："+result);
			JSONObject object = JSON.parseObject(result);
			JSONObject info = object.getJSONObject("info");
			JSONArray rows = info.getJSONArray("rows");
			List<String> set = new ArrayList<>();
			if(CollectionUtils.isEmpty(rows)){
				log.info("获取的内管租户为空");
				return set;
			}

			for (int i = 0; i < rows.size(); i++) {
				JSONObject jsonObject = rows.getJSONObject(i);
				String code = jsonObject.getString("Code");
				set.add(code);
			}
			set = set.stream().distinct().collect(Collectors.toList());
			return set;
		} catch (RestClientException e) {
			e.printStackTrace();
			log.info("获取内管租户异常:"+e);
			return null;
		}
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 增量储存租户信息
	 * @Param:
	 * @return:
	 * @Date: 2021/1/12
	 */
	@Override
	public DbResponse syncTenant(JSONObject jsonObject) {
		JSONObject info = jsonObject.getJSONObject("info");
		JSONArray data = info.getJSONArray("data");
		String opType = info.getString("opType");
		List<String> arrayList = new ArrayList<>();
		for (int i = 0; i <data.size() ; i++) {
			JSONObject dataJSONObject = data.getJSONObject(i);
			String code = dataJSONObject.getString("code");
			arrayList.add(code);
		}
		DbResponse dbResponse = null;
		if (ConstantCode.SynEurmOpType.INSERT.equals(opType)) {
			dbResponse = this.initDBData(arrayList);
		}
		return dbResponse;
	}
}
